import React, { useRef, useState, useEffect } from 'react';
import { Form, Space, Button, Table, Input, Row, Col, message, Modal, Checkbox, Tree, Tag } from 'antd';
import { SyncOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { CmdbContent, CmdbHeader, Authorized } from '@/components';
import '../../index.less'
import { useHistory, useLocation } from 'react-router-dom';
function TemplateGrouptAdd () {
  const taskListRef = useRef();
  const [form] = Form.useForm();
  const history = useHistory();
  const location = useLocation();
  const [editingTask, setEditingTask] = useState(null);
  const [processList, setProcessList] = useState([]);
  // 新增状态
  const [modalVisible, setModalVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedTemplates, setSelectedTemplates] = useState([]);
  const [initialFormValues, setInitialFormValues] = useState({}); // 添加初始表单值状态
  const [templateList, setTemplateList] = useState([
    // 模拟数据，实际项目中应从API获取
    { key: '1', templateName: '模块模板1', templateId: '32123', description: '这是模块模板1', createTime: '2023-06-01 10:30:00' },
    { key: '2', templateName: '模块模板2', templateId: '32124', description: '这是模块模板2', createTime: '2023-05-28 15:45:00' },
    { key: '3', templateName: '对象存储业务模板', templateId: '32125', description: '这是对象存储业务模板', createTime: '2023-05-20 09:15:00' },
    { key: '4', templateName: '模块模板3', templateId: '32126', description: '这是模块模板3', createTime: '2023-05-15 14:20:00' },
    { key: '5', templateName: '模块模板4', templateId: '32127', description: '这是模块模板4', createTime: '2023-05-10 11:05:00' }
  ]);
  useEffect(() => {
    // 从路由状态获取任务数据
    const { state } = location;
    console.log('location', location)
    if (state?.isEdit && state?.task) {
      setEditingTask(state.task);
      // 填充表单数据
      const formValues = {
        ossFileUploadTaskName: state.task.ossFileUploadTaskName,
        objectStoragedes: state.task.objectStoragedes
      };
      form.setFieldsValue(formValues);
      setInitialFormValues(formValues); // 保存初始表单值
      // 设置进程列表
      setProcessList(state.task.processes || []);
    } else {
      // 非编辑模式，重置表单和进程列表
      setEditingTask(null);
      setProcessList([]);
      form.resetFields();
    }
  }, [location, form]);
  const [deployedTemplates, setDeployedTemplates] = useState([]);

  const items = [
    {
      label: '模版名称',
      name: 'ossFileUploadTaskName',
      rules: [{ required: true, message: '请输入模版名称' }],
      children: <Input autoComplete="off" placeholder="请输入模版名称" />,
    },
    {
      label: '模版描述',
      name: 'objectStoragedes',
      style: { marginLeft: '10px', width: '59%' },
      children: <Input autoComplete="off" placeholder="请输入模版描述" />,
    },
  ];

  const renderItem = (props, index) => {
    return (
      <Row key={props.name ?? index} >
        <Form.Item style={{ width: '60%' }} {...props} />
      </Row>
    );
  };

  // 生成树形数据
  const generateTreeData = () => {
    // 添加根节点"集群模版名称"
    return [{
      title: (
        <span className="root-node" style={{ fontWeight: 'bold' }}>
          集群模版名称
        </span>
      ),
      key: 'root',
      children: deployedTemplates.map(template => ({
        title: (
          <span className="template-item" style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
            {template.templateName}(ID:{template.templateId})
            <DeleteOutlined
              className="delete-icon"
              style={{ marginLeft: '10px', opacity: 0, cursor: 'pointer' }}
              onClick={() => removeTemplate(template.key)}
            />
          </span>
        ),
        key: template.key,
        children: [],
      }))
    }];
  };

  // 移除模板
  const removeTemplate = (key) => {
    setDeployedTemplates(deployedTemplates.filter(template => template.key !== key));
    message.success('删除成功');
  };

  // 筛选模板列表
  const filteredTemplateList = templateList
    .filter(template => template.templateName.includes(searchKeyword))
    .sort((a, b) => new Date(b.createTime) - new Date(a.createTime));

  // 表格列定义
  const columns = [
    {
      title: '模板名称',
      dataIndex: 'templateName',
      key: 'templateName',
    },
    {
      title: '模板ID',
      dataIndex: 'templateId',
      key: 'templateId',
    },
    {
      title: '模板描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];

  // 添加模块模版
  const handleAddProcess = () => {
    setModalVisible(true);
    setSelectedTemplates([]);
  };

  // 确认选择模板
  const handleConfirmSelection = () => {
    const newTemplates = selectedTemplates.map(key =>
      templateList.find(template => template.key === key)
    ).filter(Boolean);

    // 新添加的模板放在后面
    setDeployedTemplates([...deployedTemplates, ...newTemplates]);
    setModalVisible(false);
    message.success('添加成功');
  };

  // 处理选择变化
  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedTemplates(newSelectedRowKeys);
  };

  return (
    <CmdbContent>
      <Space>
        <Button
          type="link"
          onClick={() => {
            history.goBack();
          }}
        >
          返回
        </Button>

        <CmdbHeader title={location.state?.record?.templateId ? "编辑集群模版" : "新建集群模版"} />
      </Space>


      <div className="back-white padding-10">
        <div className="padding-10">
          <div className="padding-10">
            <Space>
              <div className='base_information'>基础信息  </div>
              <div className='base_information_content'>1-1</div>
            </Space>
            <div className="padding-10">
              <Form form={form} layout="horizontal">
                {items.map(renderItem)}
              </Form>
            </div>
          </div>
          <div className="padding-10">
            <Space>
              <div className='base_information'>部署拓扑 </div>
          
              </Space>
        
          </div>
          <Button onClick={handleAddProcess}>添加模块模版</Button>
          {/* 树形展示已添加的模板 */}
          <div className="template-tree-container" style={{ marginTop: '20px', padding: '10px 0 10px 20px', border: '1px solid #e8e8e8', borderRadius: '4px' }}>
            {deployedTemplates.length > 0 ? (
              <Tree
                className="template-tree"
                defaultExpandAll
                treeData={generateTreeData()}
                showLine={{ showLeafIcon: false }}
              />
            ) : (
              <div style={{ color: '#999', textAlign: 'center', padding: '20px' }}>暂无已添加的模板</div>
            )}
          </div>
        </div>
        <Space className="padding-10">
          <Button onClick={() => {
            Modal.confirm({
              title: '确认取消本次操作?',
              okText: '确定',
              cancelText: '取消',
              centered: true, // 弹窗居中
              onOk: () => {
                setProcessList([]);
                setDeployedTemplates([]); // 清空已添加的模板
                form.resetFields();
                message.success('取消成功');
              }
            });
          }}>取消</Button>
          <Button type="primary" onClick={() => {
            form.validateFields()
              .then(values => {
                const newTask = {
                  // 生成唯一ID（实际项目中可能由后端生成）
                  temid: `JK${Date.now().toString().slice(-7)}`,
                  ossFileUploadTaskName: values.ossFileUploadTaskName,
                  objectStoragedes: values.objectStoragedes || '',
                  author: '当前用户', // 实际项目中应从登录信息获取
                  createTime: new Date().toLocaleString(),
                  updataTime: new Date().toLocaleString(),
                  status: 'check-success',
                  // 添加部署拓扑信息
                  deployedTemplates: deployedTemplates
                };

                // 保存到localStorage
                const existingTasks = JSON.parse(localStorage.getItem('tasks') || '[]');
                existingTasks.push(newTask);
                console.log(newTask);
                
                

                // 触发任务更新事件，通知TaskList表格刷新
                window.dispatchEvent(new Event('taskUpdated'));

                if (location.state &&location.state.record.templateId) {
                  // 编辑模式：更新现有任务
                  const index = existingTasks.findIndex(task => task.temid === editingTask.temid);
                  if (index !== -1) {
                    existingTasks[index] = newTask;
                  } else {
                    // 如果找不到对应任务，可能已被删除，这里可以选择添加或提示
                    existingTasks.push(newTask);
                  }
                  message.success('更新成功');
                  history.push('/template/group');
                } else {
                  // 新增模式：添加新任务
                  existingTasks.push(newTask);
                  message.success('保存成功');
                  history.push('/template/group');
                }
                localStorage.setItem('tasks', JSON.stringify(existingTasks));
                //  触发任务更新事件，通知TaskList表格刷新
                window.dispatchEvent(new Event('taskUpdated'));

    
              })
              .catch(info => {
                console.log(info);
              });
          }}>保存</Button>
        </Space>
      </div>

      {/* 添加模块模板弹窗 */}
      <Modal
        title="添加模块模板"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button key="confirm" type="primary" onClick={handleConfirmSelection}>
            确定
          </Button>,
        ]}
        width={700}
      >
        <div style={{ marginBottom: 16 }}>
          <Input
            placeholder="请输入模板名称查询"
            prefix={<SearchOutlined />}
            value={searchKeyword}
            onChange={e => setSearchKeyword(e.target.value)}
          />
        </div>
        <Table
          columns={columns}
          dataSource={filteredTemplateList}
          rowKey="key"
          pagination={{
            pageSize: 10,
            showSizeChanger: false,
            showTotal: (total) => `共 ${total} 条数据`
          }}
          rowSelection={{
            selectedRowKeys: selectedTemplates,
            onChange: onSelectChange,
          }}
        />
      </Modal>

  
    </CmdbContent>
  );
};

export default TemplateGrouptAdd;